Below is an example of how to populate a DataTable using a DataReader in C#.

First, let’s create the database table as showing below:

Design View

Table-Programming-Language-Design

SQL

CREATE TABLE [dbo].[ProgrammingLanguage] (
    [ID]           INT           NOT NULL,
    [LanguageName] NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([ID] ASC)
);

Then add a few records to that table:

Table-Programming-Language-Data-full

Now create the function that will return the return the DataTable. The function will connect the table above and execute a SQL DataReader into a DataTable:

C#

protected DataTable  FromDataReaderToDataTable()

       {
           string connectionStr = "Data Source=TotorialsPanel-PC\SQLEXPRESS; Initial Catalog=TutorialsPanel;Integrated Security=True;";

           SqlConnection cn = new SqlConnection(connectionStr);
           SqlDataAdapter da = new SqlDataAdapter();
           SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
           DataTable dtLanguages = new DataTable();
           cmd.CommandText = "Select * from ProgrammingLanguage Order by LanguageName ASC";
           cmd.Connection = cn;
           cn.Open();
           using (SqlDataReader reader = cmd.ExecuteReader())
           {
        
               dtLanguages.Load(reader);
           }

           return dtLanguages;
       }

Make sure to add the namespace below to your solution. The System.Text namespace will be used later to create a string builder.

using System.Data.SqlClient;
using System.Linq;
using System.Text;

To display the data in that DataTable, create a WinForm application in C# using Visual Studio, then add the following code within the form load event of the main form:

C#

private void frm_Load(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                StringBuilder sb = new StringBuilder();
                dt = FromDataReaderToDataTable();

                foreach (DataRow dr in dt.Rows)
                {
                    sb.AppendLine(dr[1].ToString());
                }
                MessageBox.Show(sb.ToString());
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

Now run the application. The output should be as shown below.

ProgrammingLanguage msg

 

Last modified: March 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.